<?php

include_once "IModel.php";
include_once "UserPage.php";
include_once "UserPageDAO.php";
include_once "ImageEditor.php";

class RegisterModel implements IModel {
	
	public function getData($params) {
		$data=null;
		$data->wrongfile=null;
		if($params->action == 'registerUser') {
			$data->headerEntries[] = '<meta HTTP-EQUIV="REFRESH" content="2; url='.URI::getUrl('login').'">';
			$user=new User();
			$user->setLogin($params->postParams->login);
			$user->setPass($params->postParams->pass);
			$user->setMail($params->postParams->mail);
			$avat=$params->files->avatar['name'];
			$targetPath = null;
			if($avat!=null) {
				$targetPath = URI::getAvatarsUploadDir();
				//$target_path = $target_path . basename($params->files->avatar['name']);
				$type = ImageEditor::getType(basename($params->files->avatar['name']));
				if($type == ImageEditor::TYPE_UNKNOWN) {
					$data->wrongfile=1;
					return $data;
				}
				$targetPath .= '/'.$params->postParams->login.'.'.ImageEditor::getExtension($type);
				list($width, $height) = ImageEditor::getSize($params->files->avatar['tmp_name']);
				if($width > $height)
					$image = ImageEditor::resizeToWidth($params->files->avatar['tmp_name'], Config::AVATAR_WIDTH, $type);
				else
					$image = ImageEditor::resizeToHeight($params->files->avatar['tmp_name'], Config::AVATAR_HEIGHT, $type);
				//echo $targetPath;
				ImageEditor::saveImage($image, $type, $targetPath);
				//move_uploaded_file($params->files->avatar['tmp_name'], $target_path);
			}
			if($targetPath == null)
				$targetPath = URI::getAvatarsUploadDir()."/default.png";
			$user->setAvatar($targetPath);
			try {
				UserDAO::getInstance()->addUser($user);
			}
			catch(UserExistsException $e) {
				$data->headerEntries[] = '<meta HTTP-EQUIV="REFRESH" content="0; url='.URI::getUrl('register', null, 'index').'">';
				return null;
			}			
		}
		return $data;
	}
}

?>